<?php
namespace app\common\component\help_to;

use think\Session;

class HelpToService {
	public function create($data) {
		$data['order_id'] = 'TO' . date('YmdHis') . rand(1000, 9999);

		$helpToModel = new HelpToModel($data);

    	if($helpToModel -> save()) {
    		return [
    			'code' => 0,
    			'message' => '帮助打款创建成功!',
    			'data' => [
    				'help_to' => $helpToModel
    			]
    		];
    	}

    	return [
			'code' => -1,
			'message' => '帮助打款创建失败!'
		];
	}

	public function update($data, $help_to_id) {
		$updateHelpTo = (new HelpToModel()) -> where('help_to_id', $help_to_id) -> update($data);

    	if($updateHelpTo) {
    		return [
    			'code' => 0,
    			'message' => '打款修改成功'
    		];
    	}

    	return [
			'code' => -1,
			'message' => '打款修改失败'
		];
	}
	
	public function getHelpTos($status = null, $page = 10) {
		$helpToModel = (new HelpToModel()) -> alias('h_t')
		-> join('league_help_get h_g', 'h_g.help_get_id = h_t.help_get_id')
		-> join('league_user u', 'h_g.user_id = u.user_id')
		-> field(
			'h_t.help_to_id, h_t.help_get_id, h_t.user_id h_t_user_id, h_t.order_id, h_t.money, h_t.create_time, h_t.begin_time, h_t.end_time, h_t.status, h_t.pic, h_t.help_get_from, ' .
			'h_g.user_id h_g_user_id, ' .
			'u.username, u.realname, u.phone, u.bank_code'
		)
		-> where('h_t.user_id', Session::get('user_id'));

		if(!is_null($status)) {
			$helpToModel -> where('h_t.status', $status);
		}

		return $helpToModel -> order('h_t.status ASC, h_t.help_to_id ASC') -> paginate($page, true);	
	}

	public function getAll($page = 10, $simple = true) {
		$helpToModel = (new HelpToModel()) -> alias('h_t')
		-> join('league_user u', 'h_t.user_id = u.user_id')
		-> field(
			'h_t.help_to_id, h_t.help_get_id, h_t.user_id, h_t.order_id, h_t.money, h_t.create_time, h_t.begin_time, h_t.status, h_t.pic, h_t.help_get_from, ' .
			'u.username, u.realname, u.phone, u.bank_code'
		);

		return $helpToModel -> order('h_t.status ASC, h_t.help_to_id DESC') -> paginate($page, $simple);
	}

	public function getHelpTo($help_to_id) {
		$getHelpTo = HelpToModel::get($help_to_id);
		if($getHelpTo) {
			return [
				'code' => 0,
				'message' => 'Success',
				'data' => [
					'help_to' => $getHelpTo
				]
			];
		}

		return [
			'code' => -1,
			'message' => '打款订单不存在!'
		]; 
	}
}
?>